import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message, Popconfirm, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {SortOrder} from "antd/es/table/interface";

import {
  deleteRoleUsingPost,
  pageRoleUsingPost,
  saveRoleUsingPost
} from "@/services/easyapi/eRoleCenter";
import RoleAddModel from "@/pages/RoleManage/components/RoleAddModel";
import RoleEmpower from "@/pages/RoleManage/components/RoleEmpower";


const RoleManage: React.FC = () => {
  const [empowerVisible, setEmpowerVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.PageRoleVo>();
  const [showAddRole,setShowAddRole] = useState<boolean>(false)

  const deleteRole = async (id:number)=>{
    const res = await deleteRoleUsingPost({
      id:id
    });
    if (res.code===200){
      message.success('删除成功')
    } else{
      message.error(res.msg)
    }
    actionRef.current?.reload();
  }

  // @ts-ignore
  const columns: ProColumns<API.PageRoleVo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch:true
    },
    {
      title: '角色名',
      dataIndex: 'roleName',
      valueType: 'text',
      tooltip:'角色名命名后不能更改',
      formItemProps:{
        rules:[
          {required:true,message:'请填写角色名'},
          {max:20,message:'角色名不能超过20个字符'}
        ]
      }
    },
    {
      title: '角色描述',
      dataIndex: 'roleDesc',
      valueType: 'textarea',
      search: false,
      formItemProps:{
        rules:[
          {max:255,message: '描述不能超出255字符'}
        ]
      }
    },
    {
      title: '角色类型',
      dataIndex: 'roleType',
      hideInForm: true,
      valueEnum:{
        0:{
          text:<Tag color={'green'}>系统内置</Tag>
        },
        1:{
          text:<Tag color={'blue'}>自定义</Tag>
        }
      }
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      hideInForm: true,
      search:false
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      hideInForm: true,
      search:false
    },
    {
      title: '创建时间',
      hideInForm: true,
      search: false,
      dataIndex: 'createAt',
      valueType: 'dateTime',
    },
    {
      title: '更新时间',
      search: false,
      hideInForm: true,
      dataIndex: 'updateAt',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.roleType===1?
        <a
          key="config"
          onClick={() => {
            setEmpowerVisible(true)
            setCurrentRow(record)
          }}
        >
          授权
        </a>:<></>,
        record.roleType===1?
          <Popconfirm
            title={"确定要删除该角色吗"}
            onConfirm={()=>{
              //@ts-ignore
              deleteRole(record.id)
            }}
            okText="是"
            cancelText="否"
          >
        <a
          key="config1"
          style={{color:'red'}}
        >
        删除
        </a>
         </Popconfirm>:<></>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.PageRoleVo, API.PageRoleParam>
        headerTitle={'用户列表'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={()=>[
          <Button key={"addRole"} type={'primary'} onClick={()=>setShowAddRole(true)}>新建角色</Button>
        ]}
        request={async (params,
                        sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const res = await pageRoleUsingPost({
            ...params
          } as API.PageRoleParam);
          if (res.code === 200) {
            return {
              // @ts-ignore
              data: res?.data.records,
              success: true,
              // @ts-ignore
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />
      <RoleAddModel columns={columns} onCancel={()=>setShowAddRole(false)} onSubmit={async (values)=>{
       const res =  await saveRoleUsingPost({
          roleName:values.roleName,
          roleDesc:values.roleDesc
        });
        if (res.code===200) {
          message.success('添加成功')
        } else {
          message.success('添加失败')
        }
        actionRef.current?.reload();
        setShowAddRole(false);
      }} visible={showAddRole}/>
      {/*@ts-ignore*/}
      <RoleEmpower role={currentRow} visible={empowerVisible} onCancel={()=>{
        setEmpowerVisible(false)
      }}/>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.roleName && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.roleName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default RoleManage;
